#include "server.h"

extern MYSQL* mySql;

//改变当前工作目录，若路径名错误则返回-1
int CdDir(char* pathName, int userId){
    int fileId;
    int parentId = -1;
    char cwd[1024] = {0};
    int lengthOfCwd = 0;
    char spliceName[1024] = {0};
    int lengthOfSplice = 0;
    //获取用户提供的路径名对应的文件id
    int ret = PathnameAnalyse(pathName, userId, &fileId);
    printf("fileid = %d, ret = %d\n", fileId, ret);
    if(ret == DIR_NAME) {
        //是目录文件，开始获取用户根目录到该目录文件的路径
        do {
            char querySentence[2048] = {0};
            sprintf(querySentence, 
                    "select parent_id, filename from filesystem where id = %d", fileId);
            ret = mysql_query(mySql, querySentence);
            if(ret != 0) {
                printf("query error: %s\n", mysql_error(mySql));
                return -1;
            }
            MYSQL_RES* result = mysql_store_result(mySql);
            if(result == NULL) {
                printf("query error: %s\n", mysql_error(mySql));
                return -1;
            }
            MYSQL_ROW row = mysql_fetch_row(result);
            parentId = atoi(row[0]);
            memset(spliceName, 0, sizeof(spliceName));
            strcpy(spliceName, row[1]);
            printf("%s\n", spliceName);
            mysql_free_result(result);
            //向上一级
            fileId = parentId;
            //对当前工作目录进行拼接
            lengthOfSplice = strlen(spliceName);
            memmove(cwd + lengthOfSplice + 1, cwd, lengthOfCwd);
            cwd[lengthOfSplice] = '/';
            memcpy(cwd, spliceName, lengthOfSplice);
            lengthOfCwd = strlen(cwd);
            printf("%s\n", cwd);
        } while(parentId != -1);
        //去掉最后的/
        cwd[lengthOfCwd - 1] = 0;
        //路径获取完成，插入数据库
        char querySentence[2048] = {0};
        sprintf(querySentence, 
                "update user set pwd = '%s' where id = %d", cwd, userId);
        ret = mysql_query(mySql, querySentence);
        if(ret != 0) {
            printf("query error: %s\n", mysql_error(mySql));
            return -1;
        }
        return 0;
    } else {
        //是普通文件或路径名错误，返回-1
        return -1;
    }
}



